# from appium.webdriver.common.touch_action import TouchAction
# import time
from appium import webdriver
from appium.webdriver.webdriver import WebDriver
import os
import re
from .test_cases import get_test_case
test_py_pattern = re.compile("test_(\d+?).py")


driver = None


def init_driver():
    global driver
    caps = {
        "platformName": "Android",
        "deviceName": "127.0.0.1:62001",
        "appPackage": "com.tencent.videolite.android",
        "appActivity": ".ui.HomeActivity",
        # 处理无法输入中文的问题
        'unicodeKeyboard': True,  # 使用unicodeKeyboard的编码方式来发送字符串
        'resetKeyboard': True  # 将键盘给隐藏起来
    }

    driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", caps)

    try:
        driver.find_element_by_id(
            "com.tencent.videolite.android:id/button2").click()
    except Exception:
        pass
    try:
        driver.find_element_by_id(
            "com.android.packageinstaller:id/permission_allow_button").click()
    except Exception:
        pass
    try:
        driver.find_element_by_id(
            "com.tencent.videolite.android:id/button1").click()
    except Exception:
        pass
    return driver


def _get_driver():
    global driver
    # 在模拟器上用下面方法可以不用每次都重装
    # 似乎在真机上不行
    # 会 - waiting for device -
    if driver is None:
        init_driver()
    else:
        driver.start_activity(
            "com.tencent.videolite.android", ".ui.HomeActivity")
    return driver


# 获取driver，打开腾讯视频极速版
# test_path 是测试python文件的路径（也可以填实际测试路径，但这样工作量大一些）
# 返回driver
def get_driver(test_path=None) -> WebDriver:
    if test_path is not None:
        print_test_path(test_path)
    _driver = _get_driver()
    return _driver

def close_driver():
    driver.close()


def get_test_module_name(test_path):
    assert test_path is None or isinstance(test_path, str)
    if test_path is None:
        return None
    else:
        try:
            abs_path = os.path.abspath(test_path)
            ls = abs_path.split(os.path.sep)
            module_name = ls[-2]
            return module_name
        except Exception as e:
            print(e)
            raise e


def get_test_module_name_and_id(test_path):
    assert test_path is None or isinstance(test_path, str)
    if test_path is None:
        return None, None
    else:
        try:
            abs_path = os.path.abspath(test_path)
            ls = abs_path.split(os.path.sep)
            module_name = ls[-2]
            num = test_py_pattern.findall(ls[-1])
            return module_name, int(num[0])
        except Exception as e:
            print(e)
            raise e


def print_test_path(test_path, test_id: int = None):
    assert test_path is None or isinstance(test_path, str)
    if test_path is None:
        test_path = "(Not Defined)"
    else:
        try:
            abs_path = os.path.abspath(test_path)
            ls = abs_path.split(os.path.sep)
            module_name = ls[-2]
            if test_id is None:
                num = test_py_pattern.findall(ls[-1])
                assert num
                num = num[0]
            else:
                num = test_id
            tc = get_test_case(module_name,num)
            assert tc
            test_path = tc
        except Exception as e:
            print(e)
            raise e
    try:
        print("__path__:{}:{}: {}".format(module_name,num,test_path))
    except:
        print("__path__: None")
